package br.com.ebc.icontatos.converter;

import javax.annotation.Resource;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import br.com.ebc.icontatos.model.Emissora;
import br.com.ebc.icontatos.repository.EmissoraRepository;

public class EmissoraConverter implements Converter{

	@Resource
	private EmissoraRepository emissoraDAO;
	
	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		if (value == null || value.length() == 0 || value.equals("-- Selecione --")) {
            return null;
        }
		
		Long id = new Long(value);
		Emissora p = new Emissora();
		p.setIdEmissora(id);
		p = emissoraDAO.find(p.getIdEmissora());
		return p;
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object value) {
		if (value == null) {
            return null;
        }
		
		if(value instanceof Emissora){
			Emissora p = (Emissora) value;
			return p.getIdEmissora() == null ? "" : p.getIdEmissora().toString(); 
		} else {
			throw new IllegalArgumentException("object " + value + " is of type " + value.getClass().getName() + "; expected type: model.Emissora");
		}
	}

	public EmissoraRepository getEmissoraDAO() {
		return emissoraDAO;
	}

	public void setEmissoraDAO(EmissoraRepository emissoraDAO) {
		this.emissoraDAO = emissoraDAO;
	}

}
